<template>
  <div class="page">
    <nav-bar title="走访上报" border></nav-bar>
    <div class="page-main" style="margin-top: 44px">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <template v-if="$route.query.idTypeName">
            <van-field
              required
              readonly
              name="idTypeName"
              v-model="formParams.idTypeName"
              label="证件类型"
              placeholder="请选择"
              right-icon="arrow"
              class="van-field__right-icon-white"
              label-class="van-cell__title_gray"
              :rules="rules.idTypeName"
            />
          </template>
          <template v-else>
            <van-field
              required
              readonly
              clickable
              name="idTypeName"
              v-model="formParams.idTypeName"
              label="证件类型"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.idTypeName"
              @click="dictOpenPopup('idType')"
            />
          </template>
          <van-field
            required
            name="idCard"
            v-model="formParams.idCard"
            label="证件号码"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :rules="formParams.idType === '111' ? rules.idCard : rules.passport"
            :label-class="$route.query.idCard ? 'van-cell__title_gray' : ''"
            :readonly="Boolean($route.query.idCard)"
          />
          <van-field
            required
            readonly
            name="personName"
            v-model="formParams.personName"
            label="走访人员"
            right-icon="arrow"
            class="van-field__right-icon-white"
            label-class="van-cell__title_gray"
          />
          <van-field
            required
            readonly
            name="labelName"
            v-model="formParams.labelName"
            label="走访人员标签"
            right-icon="arrow"
            class="van-field__right-icon-white"
            label-class="van-cell__title_gray"
          />
          <van-field required label="走访记录" readonly :border="false" />
          <van-field
            required
            name="intervieweeDetail"
            v-model="formParams.intervieweeDetail"
            placeholder="请输入走访记录"
            rows="5"
            autosize
            type="textarea"
            show-word-limit
            :border="false"
            input-align="left"
            class="van-field__value--textarea"
            maxlength="500"
            :rules="rules.intervieweeDetail"
          />
          <van-field label="现场照片/视频" readonly :border="false">
            <template #input>
              <van-radio-group v-model="accept" direction="horizontal">
                <van-radio name="image/*">照片</van-radio>
                <van-radio name="video/*">视频</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field class="van-field__value--upload" input-align="left" :border="false">
            <template #input>
              <van-uploader
                name="fileList"
                v-model="fileList"
                max-count="9"
                capture="camera"
                :accept="accept"
                :max-size="maxSize"
                :preview-image="previewImage"
                :before-read="uploadBeforeRead"
                :after-read="uploadAfterRead"
                @click-preview="previewClick"
              >
                <template #preview-cover="file">
                  <template v-if="format.includes(file.file.name.split('.')[file.file.name.split('.').length - 1])">
                    <div class="van-uploader__preview-masker"></div>
                    <video-player
                      class="video-player vjs-custom-skin"
                      :playsinline="true"
                      :options="{
                        aspectRatio: '16:16',
                        sources: [
                          {
                            src: $config.ImageURl + file.file.url
                          }
                        ]
                      }"
                    ></video-player>
                  </template>
                </template>
                <div class="van-uploader__input--white">
                  <div class="van-uploader__input--content">
                    <div class="upload-image">
                      <img src="@/assets/images/basic/icon_camera@2x.png" />
                    </div>
                    <div class="upload-text">点击拍摄</div>
                  </div>
                </div>
              </van-uploader>
            </template>
          </van-field>
          <div style="margin: 60px 16px">
            <van-row :gutter="23">
              <van-col span="12">
                <template v-if="$route.query.personCode">
                  <van-button block native-type="button" @click="$router.go(-1)">取消</van-button>
                </template>
                <template v-else>
                  <van-button block native-type="button" @click="onClear">清空</van-button>
                </template>
              </van-col>
              <van-col span="12">
                <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
              </van-col>
            </van-row>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
      />
    </van-popup>
    <!-- 视频预览 -->
    <gb-video :url="videoUrl" :show.sync="videoPopupShow"></gb-video>
  </div>
</template>
<script>
import Upload from '@/mixins/upload'
import InspectVisit from '@/api/inspectVisit'
import SelectPopup from '@/mixins/selectPopup'
import { residentNameReg, idCardCheck, passPortCardReg } from '@/libs/regexp'
class FormParams {
  constructor() {
    // 网格编码
    this.gridCode = ''
    // 被走访人员
    this.interviewee = ''
    // 被走访人员姓名
    this.personName = ''
    // 被走访人员证件类型
    this.idType = ''
    this.idTypeName = ''
    // 被走访人员证件号
    this.idCard = ''
    // 被走访人员标签
    this.labelCode = ''
    this.labelName = ''
    // 走访记录
    this.intervieweeDetail = ''
    // 图片
    this.imageUrl = ''
  }
}
export default {
  mixins: [Upload, SelectPopup],
  data() {
    return {
      folder: 'inspection/person',
      accept: 'image/*',
      maxSize: 50 * 1024 * 1024,
      fileList: [],
      format: ['mp4', 'avi', 'mov'],
      videoPopupShow: false,
      videoUrl: '',

      dictTypes: 'idType',

      formParams: new FormParams(),
      rules: {
        personName: [
          { required: true, message: '请输入走访人员' },
          { pattern: residentNameReg, message: '请输入中文、英文和"·"' }
        ],
        idTypeName: [{ required: true, message: '请选择证件类型' }],
        idCard: [
          { required: true, message: '请输入证件号' },
          { validator: idCardCheck, message: '请输入正确的证件号' },
          { validator: this.check, message: '暂无人员信息' }
        ],
        passport: [
          { required: true, message: '请输入证件号' },
          { pattern: passPortCardReg, message: '请输入正确的证件号' },
          { validator: this.check, message: '暂无人员信息' }
        ],
        labelName: [{ required: true, message: '请选择人员标签' }],
        intervieweeDetail: [
          { required: true, message: '请输入走访记录' },
          {
            validator: val => {
              return val.length >= 10
            },
            message: '走访记录至少输入10个字'
          }
        ]
      },
      buttonDisabled: false
    }
  },
  created() {
    // 字典项
    this.getDict(this.dictTypes)
    this.initFormParams(this.$route.query)
  },
  methods: {
    initFormParams(data) {
      if (data.personCode) {
        this.formParams.gridCode = data.gridCode
        this.formParams.interviewee = data.personCode
        this.formParams.personName = data.personName
        this.formParams.idType = data.idType
        this.formParams.idTypeName = data.idTypeName
        this.formParams.idCard = data.idCard
        this.formParams.labelCode = data.labelCode
        this.formParams.labelName = data.labelName
      }
    },
    // 视频预览
    previewClick({ file }, detail) {
      const urlArr = this.fileList[detail.index].url.split('.')
      const suffix = urlArr[urlArr.length - 1]
      if (this.format.includes(suffix)) {
        this.videoPopupShow = true
        this.videoUrl = this.$config.ImageURl + this.fileList[detail.index].url
      }
    },
    // 校验
    check() {
      if (!this.formParams.idCard || this.$route.query.idCard) return true
      return new Promise((resolve, reject) => {
        InspectVisit.Visit.check({
          idCard: this.formParams.idCard
        }).then(res => {
          if (res.data.status === 0) {
            this.initFormParams(res.data.data)
          }
          resolve(res.data.status === 0)
        })
      })
    },
    // 表单 - 校验
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    onSubmit() {
      this.formParams.gridCode = this.$route.query.gridCode
      this.formParams.imageUrl = this.fileList.map(o => o.url).join(',')
      this.buttonDisabled = true
      InspectVisit.Visit.save(this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$toast.success('提交成功')
            this.$router.go(-1)
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    },
    onClear() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否清空所有内容',
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          this.formParams = new FormParams()
          this.initFormParams(this.$route.query)
          this.$refs.from.resetValidation()
        })
    }
  }
}
</script>
